package com.norrisboat.factory

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.StdOutSqlLogger
import org.jetbrains.exposed.sql.addLogger
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction

object DatabaseFactory {

    fun connect(
        url: String,
        name: String,
        pwd: String,
        driverClz: String = "com.mysql.cj.jdbc.Driver"
    ) {
        val config = HikariConfig().apply {
            jdbcUrl = url
            username = name
            password = pwd
            driverClassName = driverClz
            maximumPoolSize = 3
            isAutoCommit = false
            transactionIsolation = "TRANSACTION_REPEATABLE_READ"
            validate()
        }

        Database.connect(HikariDataSource(config))
    }


    suspend fun <T> dbQuery(
        block: suspend () -> T
    ): T = newSuspendedTransaction {
        addLogger(StdOutSqlLogger)
        block()
    }

}